<template>
  <div class="demo-overlay">
    <van-button type="primary" @click="toggleOverlay">显示 Overlay</van-button>
    <div id="teleport-target">
      <van-button type="primary">需要被遮挡的</van-button>
    </div>

    <!-- 只有当 teleportTarget 存在时才渲染 van-overlay -->
    <van-overlay style="position: absolute; overflow: hidden;" v-if="isTargetReady" v-model:show="showOverlay"
      :teleport="teleportTarget">
      <div class="overlay-content">
        <p>这是一个通过 teleport 渲染的 Overlay</p>
        <van-button type="danger" @click="showOverlay = false">关闭</van-button>
      </div>
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const showOverlay = ref(false);
const teleportTarget = ref('#teleport-target');
const isTargetReady = ref(false); // 标记目标元素是否已准备好

// 切换 Overlay 显示状态
const toggleOverlay = () => {
  try {
    showOverlay.value = !showOverlay.value;
  } catch (error) {
    console.error('Error toggling overlay:', error);
  }
};

onMounted(() => {
  const targetElement = document.querySelector(teleportTarget.value);
  if (targetElement) {
    isTargetReady.value = true; // 目标元素存在，允许渲染 van-overlay
  } else {
    console.error('Teleport target element not found!');
  }
});
</script>

<style lang="scss" scoped>
.demo-overlay {
  width: 100%;
  height: 100%;

  #teleport-target {
    position: relative;
    width: 100%;
    height: 200px;
    line-height: 200px;
    text-align: center;
    border: 1px solid #ccc;
  }
}

.overlay-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}
</style>